
import fetch from 'isomorphic-fetch'
import { getToken } from './store'
const {buildParams,flatPostParam} = require('./base')
// export { buildParams,flatPostParam} from './base'


export default class Request {
  constructor(configs){
    this.beforeLoading = configs.beforeLoading // 接口请求前的loading加载
    this.afterLoading = configs.afterLoading   // 接口请求成功后移除loading
    this.transformResponse = configs.transformResponse // 接口请求成功后，对接口数据进行处理，返回处理后的数据
    this.responseHeaders = configs.responseHeaders // 接口请求成功后，对response.headers进行处理，比如读取headers里的token 
    this.requestHeader = configs.requestHeader // 接口请求前对headers请求头处理，比如接口需要的token参数
    this.credentials = configs.credentials || 'same-origin' // fetch credentials 属性配置
    this.defaultOptions = {
      showMsg:true, // 默认显示请求接口的错误提示
      method: this.method,
      credentials: this.credentials,
    }
  }
  buildOption(data,type) {
    let option = {}
    if(data.showMsg!==undefined){
      option.showMsg = data.showMsg
    }
    option.data = data
    option.method = type
    return option
  }
  isFunction=(fn)=>{
    return Object.prototype.toString.call(fn)==='[object Function]'
  }
  // 检查响应状态码
  checkStatus=(response)=>{
    if(this.isFunction(this.responseHeaders)){
      this.responseHeaders(response.headers)
    }
    if ((response.status >= 200 && response.status < 300)) {
      return response;
    }else{
      return {}
    }
  }
  // 检查JSON数据
  checkJson=(response)=>{
    if (response && response.json) {
      let json = response.json();
      return json
    } else {
      return response
    }
  }
  // post请求，form-data提交参数，一般用于图片上传
  form=(url,data)=>{
    return this.fetchData(url,{
      method:'post',
      body:data,
    })
  }
  // post请求，json字符串提交参数
  json = (url,data={})=>{
    let opt = this.buildOption(data,'post')
    opt.body = JSON.stringify(data)
    return this.fetchData(url,opt,{
      'Content-Type':'application/json;charset=utf-8'
    })
  }
  // post请求 form表单提交参数
  post=(url,data={})=>{
    let opt = this.buildOption(data,'post')
    opt.body = flatPostParam(opt.data)
    opt.method='post'
    return this.fetchData(url,opt,{
      'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8','Admin-Token':getToken()
    })
  }
  // get请求
  get=(url,options={})=>{
    const opt = this.buildOption(options,'get')
    let data = buildParams(opt.data)
    return this.fetchData(url+data,opt,{'Admin-Token':getToken()})
  }
  hanldeBlobFile=(res,fileName,fix)=>{
    return new Promise((rol,rej)=>{
      res.blob().then(blob => {
        var file=`${fileName}.${fix}`
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, file);  //兼容ie10
        } else {
          var a = document.createElement('a');
          document.body.appendChild(a) //兼容火狐，将a标签添加到body当中
          var url = window.URL.createObjectURL(blob);   // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
          a.href = url;
          a.download = file;
          a.target='_blank'  // a标签增加target属性
          a.click();
          a.remove()  //移除a标签
          window.URL.revokeObjectURL(url)
          rol({})
        }
      })      
    })
  }
  // 上传文档同时下载文档处理结果
  uploadAndDownload=(url,data,fileName,fix='.xlsx')=>{
    let cache=this.isFunction(this.requestHeader)?this.requestHeader():{}
    // // 默认headers头数据
    // if(this.isFunction(this.requestHeader)){
    //   cache = this.requestHeader()
    // }
    fetch(url, {
      method:'post',
      body:data,
      headers: {
        'credentials': this.credentials||'include',
        ...cache,
        'Admin-Token':getToken()
      }
    }).then(res => {
      this.hanldeBlobFile(res,fileName,fix)
    })
  }
  // 接口下载文档
  download=(url,data,fileName,fix='.xlsx')=>{
    let params = buildParams(data)
    let cache=this.isFunction(this.requestHeader)?this.requestHeader():{}
    fetch(url+params, {
      headers: {
        'credentials': this.credentials||'include',
        'Content-type': 'application/json;charset=UTF-8',
        ...cache
      }
    }).then(res => {
      this.hanldeBlobFile(res,fileName,fix)
    })
  }
  // 统一接口数据请求
  fetchData=(url,options,head)=>{
    if(this.isFunction(this.beforeLoading)){
      this.beforeLoading()
    }
    let cache={}
    // 默认headers头数据
    if(this.isFunction(this.requestHeader)){
      cache = this.requestHeader()
    }
    let newOpt = {
      ...this.defaultOptions,
      ...options,
      headers:{
        ...cache,
        ...head
      }
    }
    return new Promise((resolve,reject)=>{
      fetch(url,newOpt)
      .then(this.checkStatus)
      .then(this.checkJson)
      .then(data=>{
        if(this.isFunction(this.afterLoading)){
          this.afterLoading()
        }
        if(this.isFunction(this.transformResponse)){
          let d = this.transformResponse(data,newOpt.showMsg)
          resolve(d)
        }else{
          resolve(data)
        }
      })
      .catch((error) => {
        if(this.isFunction(this.afterLoading)){
          this.afterLoading()
        }
        console.log(error)
        // reject({})
      })
    })
  }

}
